package com.jinxin.platform.cdqzsqacs.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author : zhangpeng
 * @date : 2021-05-14 17:50:51
 **/
@Slf4j
public class Base64Utils {
    /**
     * <p>将文件转成base64 字符串</p>
     *
     * @param fileCompletePath 文件完整路径
     * @return
     */
    @SuppressWarnings("restriction")
    public static String encodeBase64File(String fileCompletePath) {
        if (StringUtils.isBlank(fileCompletePath)) {
            log.error("文件路径为空");
            return null;
        }
        File file = new File(fileCompletePath);
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return new BASE64Encoder().encode(buffer);
        } catch (FileNotFoundException e) {
            log.error("文件未找到", e);
        } catch (IOException e) {
            log.error("IO异常", e);
        } finally {
            if (inputFile != null) {
                try {
                    inputFile.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String s = encodeBase64File("C:\\Users\\Administrator\\Desktop\\face1.png");

        System.out.println(s);
    }

}
